package com.launcher.wkang.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;

import android.hardware.Camera;
import android.hardware.camera2.CameraManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;

import com.launcher.wkang.App;
import com.launcher.wkang.R;
import com.launcher.wkang.util.PhoneUtil;
public class StudentSettingActivity extends Activity implements View.OnClickListener , CompoundButton.OnCheckedChangeListener {
    private LinearLayout qrCodeLayout;
    private ImageView flashlight;
    private LinearLayout flashlightLayout;
    private LinearLayout powerSavingLayout;
    private LinearLayout lockScreenLayout;
    private LinearLayout encryptionProtectionLayout;
    private ImageView powerSaving;
    private ImageView lockScreen;
    private ImageView encryptionProtection;
    private SeekBar seekBar;
    private CheckBox isAutoChange;
    private CameraManager manager;// 声明CameraManager对象
    private boolean isLight = false;// 手电筒是否打开
    private final int  setUserLight=1001;
    private final int  setSystemLight=1002;
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        App.getINstance().setsetWaveformMode(5,1);
        setContentView(R.layout.activity_student_setting);
        initView();
        initData();
        initEvent();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.qr_code_layout:
                Intent deskTopIntent=new Intent(this, ShowQcCodeActivity.class);
                startActivity(deskTopIntent);
                break;
            case R.id.flashlight_layout:
                lightSwitch();
                break;
            case R.id.power_saving_layout:
                if (PhoneUtil.getPowerSaveMode(this)){
                    PhoneUtil.setPowerSaveMode(false,this);
                    powerSaving.setImageResource(R.mipmap.power_saving_grey);
//                    powerSaving.setImageResource(R.mipmap.unselected);
                }else {
                    PhoneUtil.setPowerSaveMode(true,this);
                    powerSaving.setImageResource(R.mipmap.power_saving_light);
                }
                break;
        }

    }

    /**
     * 初始化控件的一些操作
     */
    private void initView() {
        seekBar = (SeekBar) findViewById(R.id.seek);

        //设置最大刻度
        seekBar.setMax(255);
        //设置初始的Progress
        seekBar.setProgress(getSystemBrightness());
        //出世设置checkBox为选中状态

        //设置初始的屏幕亮度与系统一致

        qrCodeLayout=findViewById(R.id.qr_code_layout);
        qrCodeLayout.setOnClickListener(this);
        flashlightLayout=findViewById(R.id.flashlight_layout);
        flashlightLayout.setOnClickListener(this);
        flashlight=findViewById(R.id.flashlight);
        isAutoChange=findViewById(R.id.isAutoChange);
        powerSavingLayout=findViewById(R.id.power_saving_layout);
        powerSavingLayout.setOnClickListener(this);
        lockScreenLayout=findViewById(R.id.lock_screen_layout);
        lockScreenLayout.setOnClickListener(this);
        encryptionProtectionLayout=findViewById(R.id.encryption_protection_layout);
        powerSaving=findViewById(R.id.power_saving);
        lockScreen=findViewById(R.id.lock_screen);
        encryptionProtection=findViewById(R.id.encryption_protection);
    }
    /**
     * 初始化监听
     */
    private void initEvent() {
        //设置seekBar进度被改变的时候的时间监听
        seekBar.setOnSeekBarChangeListener(new MyOnSeekBarChangeListener());
        isAutoChange.setOnCheckedChangeListener(this);
        //设置CheckBox的点选监听事件

    }
    private void initData(){
        PhoneUtil.setStatusBarFullTransparent(this);
        manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        isLight=false;
            int mOldAutomatic = getScreenMode();
//
            isAutoChange.setChecked(mOldAutomatic==1);
        int hasWriteStoragePermission = ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.WRITE_SETTINGS);
        if (hasWriteStoragePermission == PackageManager.PERMISSION_GRANTED) {
            //拥有权限，执行操作
            //改变亮度
            changeAppBrightness(getSystemBrightness());
        }else{
            //没有权限，向用户请求权限
            ActivityCompat.requestPermissions(StudentSettingActivity.this, new String[]{Manifest.permission.WRITE_SETTINGS}, setSystemLight);
        }
        if (PhoneUtil.getPowerSaveMode(this)){
//            powerSaving.setImageResource(R.mipmap.power_saving_light);
//            powerSaving.setImageResource(com.launcher.wkang.R.mipmap.p);
//            powerSaving.setImageResource(R.mipmap.selected);
//            powerSaving.setImageResource(R.mipmap.power_saving_grey);
            powerSaving.setImageResource(R.mipmap.power_saving_light);
        }else {
//            powerSaving.setImageResource(com.launcher.wkang.R.mipmap.power_saving_grey);
            powerSaving.setImageResource(R.mipmap.power_saving_grey);
        }


    }

    /**
     * 改变App当前Window亮度
     *
     * @param brightness
     */
    public void changeAppBrightness(int brightness) {

        ContentResolver resolver = getContentResolver();
        Uri uri = android.provider.Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
        android.provider.Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
        resolver.notifyChange(uri, null);


    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()){

            case R.id.isAutoChange:
                if (isChecked) {
//                    手动调节
                    setScreenMode(1);
                    int seekBarProgress = seekBar.getProgress();
                    changeAppBrightness(seekBarProgress);
                } else {
//                    自动调节
                    setScreenMode(0);
                    changeAppBrightness(getSystemBrightness());
                }
                break;
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        //通过requestCode来识别是否同一个请求
        if (requestCode == setSystemLight){
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

                changeAppBrightness(getSystemBrightness());
            }
        }else if (requestCode == setUserLight){
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                int seekBarProgress = seekBar.getProgress();
                changeAppBrightness(seekBarProgress);
            }
        }
    }

    /**
     * 获得系统亮度
     *
     * @return
     */
    private int getSystemBrightness() {
        int systemBrightness = 0;
        try {
            systemBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return systemBrightness;
    }

    class MyOnSeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            //seekBar进度条被改变的时候取消checkBox的点选

            int hasWriteStoragePermission = ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.WRITE_SETTINGS);
            if (hasWriteStoragePermission == PackageManager.PERMISSION_GRANTED) {
                //拥有权限，执行操作
                //改变亮度
                if (!isAutoChange.isChecked()) {
                    changeAppBrightness(progress);
                }
            }else{
                //没有权限，向用户请求权限
                ActivityCompat.requestPermissions(StudentSettingActivity.this, new String[]{Manifest.permission.WRITE_SETTINGS}, setSystemLight);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }

    /**
     * 手电筒控制方法
     *
     * @param
     * @return
     */
    private void lightSwitch() {
                try {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        isLight=!isLight;
                        manager.setTorchMode("0", isLight);
                        if (isLight){
                            flashlight.setImageResource(R.mipmap.flashlight);
                        }else {
                            flashlight.setImageResource(R.mipmap.no_flashlight);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
    }

    /**
     * 判断Android系统版本是否 >= M(API23)
     */
    private boolean isM() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获得当前屏幕亮度的模式
     *
     * @return 1 为自动调节屏幕亮度,0 为手动调节屏幕亮度,-1 获取失败
     */
    public int getScreenMode() {
        int mode = -1;
        try {
            mode = Settings.System.getInt(getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS_MODE);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return mode;
    }
    /**
     * 设置当前屏幕亮度的模式
     *
     * @param mode 1 为自动调节屏幕亮度,0 为手动调节屏幕亮度
     */
    public  void setScreenMode(int mode) {
        try {
            Settings.System.putInt(getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS_MODE, mode);
            Uri uri = Settings.System
                    .getUriFor("screen_brightness_mode");
            getContentResolver().notifyChange(uri, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }







}
